import axios from "axios";
import { Loading } from 'element-ui';
let loading;
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url ( url = base url + request url )
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // if (config.url.indexOf("/getUserInfo") != -1) {

    //   config.baseURL = process.env.NODE_ENV== 'development'?"/api1":'https://test.x8box.com/vmcloud/api';
    //   config.params = {
    //     token: 'YreNVbwTv8icg3Uy9jXmLpu0FPf6uuZ0',
    //     userId: 60,
    //     mobilePhone: 18583342684,
    //   };
    // }
    // console.log("configconfig", config);

    // if ((config.data && config.data.loading) || (config.params && config.params.loading)) {
    //   store.commit('vant/showLoading');
    // }
    store.commit('vant/showLoading');
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["token"] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  /**
   * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
   * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;

    store.commit('vant/hideLoading');
    // code为非20000是抛错 可结合自己业务进行修改
    console.log('res.coderes.code',res.code)
    if (res.code != 200) {
      console.log('res.coderes.code2222',res.code)
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("error" + error); // for debug
    store.commit('vant/hideLoading');
    Message({
      message: error.msg,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
